import React, { useEffect, useState } from "react";
import { Button, Modal, Popconfirm, Space, Table, Row } from "antd";

import axios from "axios";
import FileSaver from "file-saver";
import xlsx from "node-xlsx";
import { useBoolean } from "ahooks";
import {
  DELETE_PRODUCT,
  GET_PRODUCT_LIST,
} from "../../../../constants/api-constants";

import Edit from "./edit";
import Detail from './show';
import Config from "./config";


export default () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<any>([]);
  const [dataSource, setDataSource] = useState<ProjectList.item[]>();
  const [currentProductUuid, setCurrentProductUuid] = useState('');
  const [page, setPage] = useState(1);
  const [name, setName] = useState("");
  const [keyword, setKeyword] = useState("");
  const [application, setApplication] = useState("");
  const [date, setDate] = useState("");
  const [loading, setLoading] = useState(false);
  const [count, setCount] = useState(0);
  const [
    isDetailShow,
    { setTrue: setDetailShow, setFalse: setDetailFalse },
  ] = useBoolean(false);
  const [
    isEditShow,
    { setTrue: setEditShow, setFalse: setEditFalse },
  ] = useBoolean(false);
  const [record, setRecord] = useState<ProjectList.item>();
  const [mainData, setMainData] = useState();
  useEffect(() => {
    setLoading(true);
    axios
      .get(GET_PRODUCT_LIST, {
        params: { page, name, keyword, fk_applicationArea: application, date },
      })
      .then((r) => {
        const { mainData } = r.data;
        console.log(mainData);
        setCount(mainData.count);
        setMainData(mainData);
        // const { patents } = mainData;
        const application_areas = mainData.application_area;
        const organizationw = mainData.organizations;
        const dataSource = mainData.rows.map((v: any, _i: number) => {
          const {
            name,
            model,
            productNo,
            unit,
            patent,
            application_area,
            registrationStatus,
            Images,
          } = v;
          const images = Images.map((image: { name: any; }, index: any) => {
            return {
              uid: index,
              name: image.name,
              status: 'done',
              url: image.name,
            }
          })
          return {
            defValue: v,
            key: v.id,
            name,
            model,
            productNo,
            organization: unit,
            patent,
            registrationStatus,
            fk_applicationArea: application_area?.name,
            // patents,
            organizationw,
            application_areas,
            images,
          };
        });
        setLoading(false);

        setDataSource(dataSource);
      })
      .catch((_r) => {
        setLoading(false);
      });
  }, [page, name, keyword, application, date]);

  const getList = () => {
    setLoading(true);
    axios
      .get(GET_PRODUCT_LIST, {
        params: { page, name, keyword, fk_applicationArea: application, date },
      })
      .then((r) => {
        const { mainData } = r.data;
        setCount(mainData.count);
        setMainData(mainData);
        // const { patents } = mainData;
        const application_areas = mainData.application_area;
        const organizationw = mainData.organizations;
        const dataSource = mainData.rows.map((v: any, _i: number) => {
          const {
            name,
            uuid,
            patent,
            model,
            productNo,
            unit,
            application_area,
            registrationStatus,
            Images,
          } = v;

          const images = Images.map((image: { name: any; }, index: any) => {
            return {
              uid: index,
              name: image.name,
              status: 'done',
              url: image.name,
            }
          })
          return {
            defValue: v,
            key: v.id,
            uuid,
            name,
            patent,
            productNo,
            model,
            organization: unit,
            registrationStatus,
            fk_applicationArea: application_area?.name,
            organizationw,
            application_areas,
            images
          };
        });
        setLoading(false);

        setDataSource(dataSource);
      })
      .catch((_r) => {
        setLoading(false);
      });
  };


  let columns = [
    {
      title: "成果名称",
      dataIndex: "name",
      key: "name",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "成果型号",
      dataIndex: "model",

      key: "model",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "所属单位",
      dataIndex: "organization",
      key: "organization",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "注册情况",
      dataIndex: "registrationStatus",
      key: "registrationStatus",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "应用领域",
      dataIndex: "fk_applicationArea",
      key: "fk_applicationArea",
      render: (text: string) => {
        return (
          <span
            style={{
              wordBreak: "break-all",
              width: "auto",
              display: "block",
              whiteSpace: "pre-wrap",
            }}
          >
            {text}
          </span>
        );
      },
    },
    {
      title: "操作",
      render: (_value: any, record: any) => {
        if (window.localStorage.getItem('identity') === null) {
          return (
            <Button
              style={{ padding: 0 }}
              onClick={() => {
                console.log(record);
                setCurrentProductUuid(record.defValue.uuid);
                setDetailShow();
              }}
              type={"link"}
            >
              详情
            </Button>
          );
        } else {
          return (
            <>
              <Space size={10}>
                <Button
                  style={{ padding: 0 }}
                  onClick={() => {
                    console.log(record);
                    setCurrentProductUuid(record.defValue.uuid);
                    setDetailShow();
                  }}
                  type={"link"}
                >
                  详情
                </Button>
                <Button
                  style={{ padding: 0 }}
                  onClick={() => {
                    setEditShow();
                    setRecord(record);
                  }}
                  type={"link"}
                >
                  修改
                </Button>
                <Popconfirm
                  title="确定删除?一经删除将无法恢复"
                  onConfirm={() => {
                    axios
                      .post(DELETE_PRODUCT, {
                        id: [record.defValue.id],
                      })
                      .then((_r) => {
                        getList();
                      })
                      .catch((_r) => {
                        getList();
                      });
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button style={{ padding: 0 }} onClick={() => { }} type={"link"}>
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            </>
          );
        }
      },
    },
  ];

  return (
    <>
      <Config
        getList={getList}
        mainData={mainData}
        setDetailShow={setEditShow}
        setRecord={setRecord}
        setDate={setDate}
        setName={setName}
        setApplication={setApplication}
        setPage={setPage}
        setKeyword={setKeyword}
      />
      <Table
        pagination={{
          current: page,
          showSizeChanger: false,
          pageSize: 10,
          total: count,
          onChange: (page, _pageSize) => {
            setLoading(true);
            setPage(page);
            setLoading(false);
          },
        }}
        loading={loading}
        size={"middle"}
        rowSelection={{
          selectedRowKeys,
          onChange: (value) => {
            setSelectedRowKeys(value);
          },
          selections: [],
        }}
        columns={columns}
        dataSource={dataSource}
        footer={() => {
          return (
            <>
              {
                window.localStorage.getItem('identity') === null ?
                  null
                  :
                  <Row justify="space-between">
                    <Space>
                      <Space>
                        <Button
                          onClick={() => {
                            if (dataSource) {
                              const data: string[][] = [
                                [
                                  "成果名称",
                                  "成果型号",
                                  "所属单位",
                                  "投资机构",
                                  "所在地",
                                  "医疗器械注册情况",
                                  "联系人姓名",
                                  "联系人电话",
                                  "联系人邮箱",
                                  "成果简介",
                                  "应用领域",
                                  "所用专利",
                                ],
                              ];
                              selectedRowKeys.forEach((v: number) => {
                                const item = dataSource.find(
                                  (value: ProjectList.item) => {
                                    return value.key === v;
                                  }
                                );
                                console.log(item);
                                if (item && item.defValue) {

                                  let organizations = "";
                                  item.defValue.organizations.forEach(
                                    (v: { name: string }, i: any) => {
                                      if (i === 0) {
                                        organizations += v.name;
                                      } else {
                                        organizations += "," + v.name;
                                      }
                                    }
                                  );
                                  data.push([
                                    item.defValue.name,
                                    item.defValue.model,
                                    item.defValue.unit,
                                    organizations,
                                    item.defValue.address,

                                    item.defValue.registrationStatus,

                                    item.defValue.contactPerson,
                                    item.defValue.contactTel,
                                    item.defValue.contactEmail,
                                    item.defValue.description,
                                    item.defValue.application_area?.name,
                                    item.defValue.patent,
                                  ]);
                                }
                              });
                              if (data.length !== 1) {
                                const blob = new Blob(
                                  [xlsx.build([{ name: "output", data }])],
                                  {
                                    type: "application/octet-stream",
                                  }
                                );
                                FileSaver.saveAs(blob, "templateOut.xlsx");
                              }
                            }
                          }}
                        >
                          批量导出
                        </Button>
                        <Popconfirm
                          title="确定删除?一经删除将无法恢复"
                          onConfirm={() => {
                            const keys = selectedRowKeys.map((v: number) => {
                              if (dataSource) {
                                return v;
                              } else {
                                return 0;
                              }
                            });
                            axios
                              .post(DELETE_PRODUCT, {
                                id: keys,
                              })
                              .then((_r) => {
                                getList();
                              })
                              .catch((_r) => {
                                getList();
                              });
                          }}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button onClick={() => { }}>批量删除</Button>
                        </Popconfirm>
                      </Space>
                    </Space>
                  </Row>
              }
            </>
          );
        }}
      />

      <Modal
        title="成果修改"
        visible={isEditShow}
        onCancel={() => {
          setEditFalse();
        }}
        cancelText
        okText
        width={"70vw"}
        footer={null}
        style={{ top: 15 }}
        destroyOnClose
      >
        <Edit
          loading={loading}
          setLoading={setLoading}
          getList={getList}
          setDetailFalse={setEditFalse}
          record={record}
        />
      </Modal>
      <Modal
        title="成果查看"
        visible={isDetailShow}
        onCancel={() => {
          setDetailFalse();
        }}
        cancelText
        okText
        width={"70vw"}
        footer={null}
        style={{ top: 15 }}
        destroyOnClose
      >
        <Detail
          setDetailFalse={setDetailFalse}
          productUuid={currentProductUuid}
        />
      </Modal>
    </>
  );
};
